package cevent.source.cloudcenter.server.service;

import cevent.source.cloudcenter.server.domain.Member;
import cevent.source.cloudcenter.server.domain.MemberExample;
import cevent.source.cloudcenter.server.dto.*;
import cevent.source.cloudcenter.server.enums.LevelEnum;
import cevent.source.cloudcenter.server.exception.BusinessException;
import cevent.source.cloudcenter.server.exception.BusinessExceptionCode;
import cevent.source.cloudcenter.server.mapper.MemberMapper;
import cevent.source.cloudcenter.server.util.DuplicateUtil;
import cevent.source.cloudcenter.server.util.UUID8Util;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * @author cevent
 * @description 会员管理表服务层
 */
@Service
public class MemberService {
    private static final Logger LOG = LoggerFactory.getLogger(MemberService.class);
    @Resource
    private MemberMapper memberMapper;

    //1.无分页列表查询：dto获取domain参数
    public List<MemberDto> memberDtoList() {
        MemberExample memberExample = new MemberExample();
        memberExample.setOrderByClause("uni_id asc");
        List<Member> memberList = memberMapper.selectByExampleWithBLOBs(memberExample);
        List<MemberDto> memberDtoList = new ArrayList<MemberDto>();
        for (int i = 0; i < memberList.size(); i++) {
            Member member = memberList.get(i);
            MemberDto memberDto = new MemberDto();
            //复制拷贝(source,target)
            BeanUtils.copyProperties(member, memberDto);
            memberDtoList.add(memberDto);
        }
        return memberDtoList;
    }

    /*2.分页查询：pageDto保存数据
        list数据集合：listPageData
        当前页码：currentPage
        每页行数：size
        总计函数：totalSize
        前端可返回pageDto，无需返回值
     */
    public void getMemberPageDtoList(PageDto pageDto) {
        //1.分页设置（前端传入当前页和每页行数params），起始页，每页行数size
        PageHelper.startPage(pageDto.getCurrentPage(), pageDto.getSize());

        MemberExample memberExample = new MemberExample();


        List<Member> memberList = memberMapper.selectByExampleWithBLOBs(memberExample);
        //2.将mapper查询结果复制到pageInfo
        PageInfo<Member> pageInfo = new PageInfo<>(memberList);
        //3.pageInfo计算处理处理=>后分页的总行数set到pageDto做记录
        pageDto.setTotalSize(pageInfo.getTotal());

        List<MemberDto> memberDtoList = new ArrayList<>();
        memberList.stream().forEach(member -> {

            JSONObject p = JSONObject.parseObject(member.getProvince());
            StoreProvinceDto province = JSONObject.toJavaObject(p, StoreProvinceDto.class);
            JSONObject c = JSONObject.parseObject(member.getCity());
            StoreCityDto city = JSONObject.toJavaObject(c, StoreCityDto.class);
            JSONObject d = JSONObject.parseObject(member.getDistrict());
            StoreDistrictDto district = JSONObject.toJavaObject(d, StoreDistrictDto.class);
            List<String> picList = new ArrayList<>();
            LOG.info("获取到的picList：{}", member.getIdentityCard());
            if (!StringUtils.isEmpty(member.getIdentityCard())) {
                picList = Arrays.asList(member.getIdentityCard().split(";"));
            }

            MemberDto memberDto = new MemberDto();
            BeanUtils.copyProperties(member, memberDto);
            memberDto.setProvince(province);
            memberDto.setCity(city);
            memberDto.setDistrict(district);
            memberDto.setIdentityCard(picList);
            memberDtoList.add(memberDto);
        });
        pageDto.setListPageData(memberDtoList);
    }

    //3.新增、修改member，将传入的id转为member对象本身
    public void save(MemberDto memberDto) {

        String province = null;
        String city = null;
        String district = null;
        if (memberDto.getProvince() != null) {
            //jsonObj转
            JSONObject jsonObject = (JSONObject) JSONObject.toJSON(memberDto.getProvince());
            //转jsonStr
            province = jsonObject.toString();
        }
        if (memberDto.getCity() != null) {
            JSONObject jsonObject = (JSONObject) JSONObject.toJSON(memberDto.getCity());
            city = jsonObject.toString();
        }
        if (memberDto.getDistrict() != null) {
            JSONObject jsonObject = (JSONObject) JSONObject.toJSON(memberDto.getDistrict());
            district = jsonObject.toString();
        }
        Member member = DuplicateUtil.copy(memberDto, Member.class);
        List<String> picList = new ArrayList<>();
        StringBuilder pics = new StringBuilder();
        if (memberDto.getIdentityCard() != null) {
            picList = memberDto.getIdentityCard();
            for (String pic : picList) {
                pics.append(pic + ";");
            }
        }
        String pic = pics.toString();

        member.setProvince(province);
        member.setCity(city);
        member.setDistrict(district);
        member.setIdentityCard(pic);

        if (StringUtils.isEmpty(memberDto.getUniId())) {
            this.insert(member);
        } else {
            this.update(member);
        }

    }

    //4.删除模块
    public void delete(String uniId) {
        MemberExample memberExample = new MemberExample();
        memberMapper.deleteByPrimaryKey(uniId);
    }

    //5.向外暴露dto，不暴露实体类：插入数据
    private void insert(Member member) {
        member.setUniId(UUID8Util.getShortUUID());
        if (member.getLevel() == null) {
            member.setLevel(LevelEnum.ONE.getCode());
        }

        try {
            Date now = new Date();
            String date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(now);
            long time = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(date).getTime();
            int timeInt = (int) (time / 1000);
            member.setCreateTime(now);
            member.setUpdateTime(now);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        memberMapper.insertSelective(member);
    }

    //6.更新模块
    private void update(Member member) {
        try {
            Date now = new Date();
            String date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(now);
            long time = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(date).getTime();
            int timeInt = (int) (time / 1000);

            member.setUpdateTime(now);
        } catch (ParseException e) {
            e.printStackTrace();
        }

        memberMapper.updateByPrimaryKeySelective(member);
    }

    //保存图片
    public List<String> savePicList(ModulePicPathDto modulePicPathDto) {
        List<String> picList = new ArrayList<>();
        Member member = memberMapper.selectByPrimaryKey(modulePicPathDto.getModuleId());
        StringBuffer sb = new StringBuffer();
        if (!StringUtils.isEmpty(member.getIdentityCard())) {
            picList = Arrays.asList(member.getIdentityCard().split(";"));
            for (String pic : picList) {
                sb.append(pic + ";");
            }
        }
        sb.append(modulePicPathDto.getPicPath() + ";");
        String pics = sb.toString();
        member.setIdentityCard(pics);
        memberMapper.updateByPrimaryKeySelective(member);
        List<String> pic = getPicList(modulePicPathDto.getModuleId());
        return pic;
    }

    private List<String> getPicList(String moduleId) {
        Member member = memberMapper.selectByPrimaryKey(moduleId);
        List<String> picList = Arrays.asList(member.getIdentityCard().split(";"));
        return picList;
    }

    //保存会员密码
    public MemberDto saveMemberPwd(MemberDto memberDto) {
        LOG.info("传入的password2：{}", memberDto.getPassword());
        Member member = new Member();
        member.setUniId(memberDto.getUniId());
        member.setPassword(memberDto.getPassword());
        member.setUpdateTime(new Date());
        memberMapper.updateByPrimaryKeySelective(member);
        MemberDto md = DuplicateUtil.copy(member, MemberDto.class);
        return md;
    }

    /**
     * 客户端用户注册
     *
     * @param memberDto
     * @return
     */
    public MemberDto memberRegister(MemberDto memberDto) {

        MemberDto memberData = getMemberPhone(memberDto.getMobile());
        if (memberData != null) {
            throw new BusinessException(BusinessExceptionCode.MEMBER_MOBILE_EXIST);
        } else {
            String province = null;
            String city = null;
            String district = null;
            if (memberDto.getProvince() != null) {
                //jsonObj转
                JSONObject jsonObject = (JSONObject) JSONObject.toJSON(memberDto.getProvince());
                //转jsonStr
                province = jsonObject.toString();
            }
            if (memberDto.getCity() != null) {
                JSONObject jsonObject = (JSONObject) JSONObject.toJSON(memberDto.getCity());
                city = jsonObject.toString();
            }
            if (memberDto.getDistrict() != null) {
                JSONObject jsonObject = (JSONObject) JSONObject.toJSON(memberDto.getDistrict());
                district = jsonObject.toString();
            }
            Member member = DuplicateUtil.copy(memberDto, Member.class);
            List<String> picList = new ArrayList<>();
            StringBuilder pics = new StringBuilder();
            if (memberDto.getIdentityCard() != null) {
                picList = memberDto.getIdentityCard();
                for (String pic : picList) {
                    pics.append(pic + ";");
                }
            }
            String pic = pics.toString();

            member.setProvince(province);
            member.setCity(city);
            member.setDistrict(district);
            member.setIdentityCard(pic);

            if (StringUtils.isEmpty(memberDto.getUniId())) {
                this.insert(member);
            } else {
                this.update(member);
            }
            MemberDto mb = DuplicateUtil.copy(member, MemberDto.class);

            return mb;
        }
    }

    //登录
    public MemberLoginDto saveLoginIp(MemberDto memberDto, HttpServletRequest httpServletRequest) {
        MemberDto memberData = getMemberPhone(memberDto.getMobile());
        Member member = new Member();
        if (memberData == null) {
            LOG.info("会员电话号不存在：{}", memberDto.getMobile());
            throw new BusinessException(BusinessExceptionCode.MEMBER_MOBILE_ERROR);
        } else {
            LOG.info("登录密码：{}，原密码：{}，登录IP：{}", memberDto.getPassword(), memberData.getPassword(), httpServletRequest.getRemoteAddr());
            if (memberDto.getPassword().equals(memberData.getPassword())) {
                if (memberData.getLoginIp() != null) {
                    List<String> loginIps = memberData.getLoginIp();
                    StringBuffer sbs = new StringBuffer();
                    for (String sb : loginIps) {
                        sbs.append(sb + ";");
                    }
                    if (!loginIps.contains(httpServletRequest.getRemoteAddr())) {
                        sbs.append(httpServletRequest.getRemoteAddr() + ";");
                    }

                    member = DuplicateUtil.copy(memberData, Member.class);
                    LOG.info("获取到的member信息：{}",member);

                    member.setLoginIp(sbs.toString());
                    memberMapper.updateByPrimaryKeySelective(member);
                }
                MemberLoginDto memberLoginDto = DuplicateUtil.copy(memberData, MemberLoginDto.class);

                List<String> identityCard = new ArrayList<>();

                LOG.info("获取到的身份证：{}",memberData.getIdentityCard());
                if (!StringUtils.isEmpty(memberData.getIdentityCard()) && memberData.getIdentityCard().size()>0) {
                    identityCard.add(Constants.MEMBER_IDENTITY_CARD);
                }
                LOG.info("新增的身份证：{}",identityCard);
                List<String> picList = new ArrayList<>();
                memberLoginDto.setProvince(memberData.getProvince());
                memberLoginDto.setCity(memberData.getCity());
                memberLoginDto.setDistrict(memberData.getDistrict());
                memberLoginDto.setIdentityCard(identityCard);

                return memberLoginDto;
            } else {
                LOG.info("会员登录密码不正确，输入密码：{} 原密码：{}", memberDto.getPassword(), memberData.getPassword());
                throw new BusinessException(BusinessExceptionCode.MEMBER_PASSWORD_ERROR);
            }
        }
    }

    public MemberDto getMemberPhone(String mobile) {
        MemberExample memberExample = new MemberExample();
        MemberExample.Criteria criteria = memberExample.createCriteria();
        criteria.andMobileEqualTo(mobile);
        List<Member> memberList = memberMapper.selectByExampleWithBLOBs(memberExample);
        if (CollectionUtils.isEmpty(memberList)) {
            return null;
        } else {
            MemberDto memberDto = DuplicateUtil.copy(memberList.get(0), MemberDto.class);
            List<String> loginIps = new ArrayList<>();
            if (!StringUtils.isEmpty(memberList.get(0).getLoginIp())) {
                loginIps = Arrays.asList(memberList.get(0).getLoginIp().split(";"));
            }
            List<String> identityCard=new ArrayList<>();
            if(!StringUtils.isEmpty(memberList.get(0).getIdentityCard())){
                identityCard=Arrays.asList(memberList.get(0).getIdentityCard().split(";"));
            }
            StoreProvinceDto provinceDto=null;
            StoreCityDto cityDto=null;
            StoreDistrictDto districtDto=null;
            if (!StringUtils.isEmpty(memberList.get(0).getProvince())) {
                //jsonObj转
                JSONObject jsonObject = JSONObject.parseObject(memberList.get(0).getProvince());
                provinceDto = JSONObject.toJavaObject(jsonObject, StoreProvinceDto.class);
            }
            if (!StringUtils.isEmpty(memberList.get(0).getCity())) {
                JSONObject jsonObject = JSONObject.parseObject(memberList.get(0).getCity());
                cityDto = JSONObject.toJavaObject(jsonObject, StoreCityDto.class);
            }
            if (!StringUtils.isEmpty(memberList.get(0).getDistrict())) {
                JSONObject jsonObject = JSONObject.parseObject(memberList.get(0).getDistrict());
                districtDto = JSONObject.toJavaObject(jsonObject, StoreDistrictDto.class);
            }
            memberDto.setLoginIp(loginIps);
            memberDto.setIdentityCard(identityCard);
            memberDto.setProvince(provinceDto);
            memberDto.setCity(cityDto);
            memberDto.setDistrict(districtDto);
            LOG.info("手机号获取到的identity：{}",memberDto);
            return memberDto;
        }
    }

    //保存账号绑定数据
    public MemberDto memberSaveSecret(MemberDto memberDto) {
        StringBuffer sb = new StringBuffer();
        String idCards=null;
        LOG.info("获取到的memberDto：{}", memberDto);
        if (memberDto.getIdentityCard().size()>0) {
            idCards=memberDto.getIdentityCard().get(0)+";";
        }
        LOG.info("这里的idCards：{}",idCards);
        Member member = new Member();
        member.setUniId(memberDto.getUniId());
        member.setEmail(memberDto.getEmail());
        member.setWechatCode(memberDto.getWechatCode());
        member.setIdentityCard(idCards);
        LOG.info("保存的身份证图片：{}", member);
        memberMapper.updateByPrimaryKeySelective(member);

        return memberDto;
    }

    //保存头像
    public String saveMemberIcon(ModulePicPathDto modulePicPathDto){
        Member member=new Member();
        member.setUniId(modulePicPathDto.getModuleId());
        member.setIcon(modulePicPathDto.getPicPath());
        memberMapper.updateByPrimaryKeySelective(member);
        String path=member.getIcon();

        return path;
    }

    //保存基本信息
    public MemberDto saveBaseInfo(MemberDto memberDto){
        LOG.info("保存基本信息：获取到的memberDto：{}", memberDto);
        Member member=DuplicateUtil.copy(memberDto,Member.class);
        String province=null;
        String city=null;
        String district=null;
        if(memberDto.getProvince()!=null){
            JSONObject jsonObject=(JSONObject) JSONObject.toJSON(memberDto.getProvince());
            province=jsonObject.toString();
        }
        if(memberDto.getCity()!=null){
            JSONObject jsonObject=(JSONObject) JSONObject.toJSON(memberDto.getCity());
            city=jsonObject.toString();
        }
        if(memberDto.getDistrict()!=null){
            JSONObject jsonObject=(JSONObject) JSONObject.toJSON(memberDto.getDistrict());
            district=jsonObject.toString();
        }
        member.setProvince(province);
        member.setCity(city);
        member.setDistrict(district);
        memberMapper.updateByPrimaryKeySelective(member);
        return memberDto;
    }
}
